package btcdemo.btcdemo.security;

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

/**
 * md5工具类
 *
 * @author blues
 */
public class Md5Utils {

    private static final String KEY_MD5 = "MD5";

    /**
     * 获取MD5加密
     *
     * @param before 需要加密的字符串
     * @return 加密后的字符串
     */
    public static String md5(String before) {
        MessageDigest md5 = null;
        try {
            md5 = MessageDigest.getInstance(KEY_MD5);
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        }
        md5.update(before.getBytes());
        return byteArrayToString(md5.digest()).toUpperCase();
    }


    /**
     * 下面这个函数用于将字节数组换成成字符串
     *
     * @param byteArray
     * @return
     */
    private static String byteArrayToString(byte[] byteArray) {
        StringBuilder builder = new StringBuilder();
        String temp;
        for (int i = 0; i < byteArray.length; i++) {
            temp = Integer.toHexString(byteArray[i] & 0xFF);
            if (temp.length() == 1) {
                builder.append("0");
            }
            builder.append(temp);
        }
        return builder.toString();
    }
}


